package com.cy.gameserver.webSockect;

import com.cy.gameserver.service.UserService;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by tiankai.qin on 18/3/14.
 * 负责请求调度
 */
@Service
@EnableScheduling
public class WebSocketDispatcher {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketDispatcher.class);

    private static Map<String, Session> sessionPool = Maps.newHashMap();
    private static Map<String, String> sessionIds = Maps.newHashMap();

    @Autowired
    private UserService userService;

    /**
     * 负责请求调度
     */
    public void doDispatch() {

    }

    public void onOpen(Session session, String token) {
        if (userService.validateToken(token)) {
            sessionPool.put(token, session);
            sessionIds.put(session.getId(), token);
        } else {
            sendMessage(session, "token无效");
            try {
                session.close();
            } catch (IOException e) {
                logger.info("session id:" + session.getId() + " 断开连接时发生错误:" + e);
            }
        }
    }

    public void onMessage(Session session, String message) {
        System.out.println("session id:" + session.getId() + " 发来了信息:" + message);
        logger.info("session id:" + session.getId() + " 发来了信息:" + message);
    }

    private String getToken(Session session) {
        return sessionIds.get(session.getId());
    }

    public void onClose(Session session) {
        sessionPool.remove(sessionIds.get(session.getId()));
        sessionIds.remove(session.getId());
    }

    public void onError(Session session, Throwable throwable) {
        System.out.println("session id:" + session.getId() + " 发生了错误 " + throwable);
        logger.info("session id:" + session.getId() + " 发生了错误 " + throwable);
    }

    public void sendMessageById(String sessionId, String message) {
        String token = sessionIds.get(sessionId);
        sendMessageByToken(token, message);
    }

    public void sendMessageByToken(String token, String message) {
        Session session = sessionPool.get(token);
        sendMessage(session, message);
    }

    public void sendMessage(Session session, String message) {
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                System.out.println("session id:" + session.getId() + " 返回信息时发生了错误 " + e);
                logger.info("session id:" + session.getId() + " 返回信息时发生了错误 " + e);
            }
        }
    }

    /**
     * 当前在线人数
     *
     * @return
     */
    public int getOnlineNum() {
        return sessionPool.size();
    }

    /**
     * 向所有连接发送信息
     *
     * @param msg
     */
    public void sendAll(String msg) {
        for (Session session : sessionPool.values()) {
            sendMessage(session, msg);
        }
    }

    @Scheduled(fixedRate = 11 * 1000)
    public void scheduledTask() throws Exception {
        sendAll("系统广播 : " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
